//
//  WKWebViewExtension.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/9/4.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import WebKit

let processPool = WKProcessPool()

extension WKWebView {
    
    static func create() -> WKWebView {
        // Webview的偏好设置
        let preferences = WKPreferences()
        preferences.minimumFontSize = 10
        preferences.javaScriptEnabled = true
        // 默认是不能通过JS自动打开窗口的，必须通过用户交互才能打开
        preferences.javaScriptCanOpenWindowsAutomatically = false
        
        // 禁止选择CSS
        let css = "body{-webkit-user-select:none;-webkit-user-drag:none;}"
        var javascript = ""
        javascript.append("var style = document.createElement('style');")
        javascript.append("style.type = 'text/css';")
        javascript.append("var cssContent = document.createTextNode('\(css)');")
        javascript.append("style.appendChild(cssContent);")
        javascript.append("document.body.appendChild(style);")
        
        let noneSelectScript = WKUserScript(source: javascript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        
        // 通过js与webview内容交互配置
        let userContentController = WKUserContentController()
        userContentController.addUserScript(noneSelectScript)
        
        // 创建一个Webview的配置项
        let configuretion = WKWebViewConfiguration()
        configuretion.preferences = preferences
        configuretion.processPool = processPool
        configuretion.userContentController = userContentController
        
        let webView = WKWebView(frame:.zero, configuration: configuretion)
        webView.customUserAgent = "Mozilla/5.0 iPhone AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A456 TH5App"
        return webView
    }
    
    static func deleteWebViewData() {
        WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date.distantPast, completionHandler: {
            yy_Log("WebView Data deleted successfully")
        })
    }
    
}
